package com.sc.form_authentation.controller;

import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class CaptchaController {

    @Autowired
    private Producer captchaProducer;

    @GetMapping("/captcha")
    @CrossOrigin
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        //设置内容类型
        response.setContentType("image/jpeg");
        //创建验证码文本
        String codeStr = captchaProducer.createText();
        //将验证码文本设置到session中
        request.getSession().setAttribute("captcha",codeStr);
        //创建图片
        BufferedImage image = captchaProducer.createImage(codeStr);
        ServletOutputStream outputStream=null;
        try {
            //获取响应输出流
            outputStream = response.getOutputStream();
            //将图片验证码数据写到响应输出流
            ImageIO.write(image,"jpg",outputStream);
            //推送并关闭响应输出流
            outputStream.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream!=null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
